package com.yonyou.pmclouds.workstopreport.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.CommonProgramConsts;
import com.yonyou.pmclouds.billview.entity.BillViewQueryVO;
import com.yonyou.pmclouds.copyperson.entity.CopyPersonVO;
import com.yonyou.pmclouds.copyperson.rmiitf.ICopyPersonQuery;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.pmpub.entity.QueryListParam;
import com.yonyou.pmclouds.pmpub.rmiitf.IPageQuerySerivce;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.workflow.service.rmiitf.IWorkFlowService;
import com.yonyou.pmclouds.workstopreport.entity.WorkStopVO;
import com.yonyou.pmclouds.workstopreport.mapper.WorkStopMapper;
import com.yonyou.pmclouds.workstopreport.rmiitf.WorkStopQuery;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = com.yonyou.pmclouds.workstopreport.rmiitf.WorkStopQuery.class)
public class WorkStopQueryImpl implements WorkStopQuery, IPageQuerySerivce<WorkStopVO> {

    @Autowired
    private WorkStopMapper workStopMapper;

    @Autowired
    private PictureRemoteService picService;

    @Autowired
    private ProjectSimpleQuery projectSimpleQuery;

    @Autowired
    private ICopyPersonQuery copyPersonQuery;

    @Autowired
    private OrganizationQuery organizationQuery;

    @Autowired
    private IWorkFlowService iworkFlowService;


    @Override
    public WorkStopVO[] queryByProject(QueryListParam param) throws BusinessException {
        WorkStopVO[] vos = workStopMapper.queryByCondition(new String[]{param.getPkProject()}, null, null, null, param.getStartDate(), param.getEndDate(), null, param.getPageStart(), param.getPageSize());
        if (null == vos || vos.length == 0) {
            return new WorkStopVO[0];
        }
        //填充图片
        fillPics(vos);

        return vos;
    }

    @Override
    public int countByProject(QueryListParam param) throws BusinessException {
        return workStopMapper.countByCondition(new String[]{param.getPkProject()}, null, null, null, param.getStartDate(), param.getEndDate(), null);
    }

    @Override
    public String getBillType() {
        return BillTypeConst.WORKSTOP_BILLTYPE;
    }

    @Override
    public PageObject<Object> queryByCondition(BillViewQueryVO billViewQueryVO) throws BusinessException {

        JSONObject extendsParams = billViewQueryVO.getExtendsParams();
        String[] pkorgs = extendsParams != null && StringUtils.isNotBlank(extendsParams.getString("pkorgs")) ? extendsParams.getString("pkorgs").split(",") : null;
        String tenantId = RuntimeEnvironment.getTenantId().trim();
        String[] pkProject = billViewQueryVO.getPkProject();
        int start = billViewQueryVO.getPageStart();
        String startDate = billViewQueryVO.getStartTime();
        String endDate = billViewQueryVO.getEndTime();
        int[] billStatus = billViewQueryVO.getBillStatus();
        String[] creators = billViewQueryVO.getCreators();
        int size = billViewQueryVO.getPageSize();

        //查询符合条件的停工单数量
        int count = workStopMapper.countByCondition(pkProject, pkorgs, tenantId, creators, startDate, endDate, billStatus);

        //查询符合条件的停工单
        WorkStopVO[] workStopVOS = workStopMapper.queryByCondition(pkProject, pkorgs, tenantId, creators, startDate, endDate, billStatus, start, size);
        //填充图片
        fillPics(workStopVOS);

        return new PageObject<Object>(workStopVOS, count, start);
    }

    @Override
    public Map<String, WorkStopVO> queryByIds(String[] ids) {
        //强制截取长度，避免insql可能的问题
        if (ids.length > CommonProgramConsts.DEFAULT_MAX_QUERY_SIZE) {
            ids = Arrays.copyOf(ids, CommonProgramConsts.DEFAULT_MAX_QUERY_SIZE);
        }

        WorkStopVO[] workStopVOS = workStopMapper.queryByIds(ids);

        if (null == workStopVOS || workStopVOS.length == 0) {
            return new HashMap();
        }

        Map<String, WorkStopVO> map = new HashMap<>();

        for (WorkStopVO workStopVO : workStopVOS) {
            map.put(workStopVO.getPkWorkstopreport(), workStopVO);
        }
        return map;
    }

    @Override
    public WorkStopVO[] queryByStatus(String pkProject, int[] status) throws BusinessException {
        return workStopMapper.queryByStatus(pkProject,status);
    }

    @Override
    public WorkStopVO getReport(String reportId) throws BusinessException {
        WorkStopVO workStopVO = workStopMapper.selectReport(reportId);
        if (null == workStopVO) {
            return new WorkStopVO();
        }
        String[] pics = picService.queryPicNamesByPkEntity(reportId);

        if (null != pics && pics.length > 0) {
            List<String> picLists = new ArrayList<>();
            //展示得时候过滤调文件（app要求，web卡片详情中没有展现出来所以不用考虑）
            for(String pic : pics){
                String[] elements = pic.split("\\.");
                if(null != elements || elements.length == 2){
                    String suffix = elements[1];
                    if(suffix.equals("png") || suffix.equals("jpg") || suffix.equals("jpeg")){
                        if(picLists.size() > 9){
                            break;
                        }
                        picLists.add(pic);
                    }
                }
            }
            workStopVO.setPictures(picLists.toArray(new String[0]));
            workStopVO.setPicNum(pics.length);
        }

        wrapStatus(workStopVO);

        List<String> list = new ArrayList<>();
        list.add(reportId);
        List<CopyPersonVO> copyPersonVOS = copyPersonQuery.queryByPkBills(list);
        if (null != copyPersonVOS && copyPersonVOS.size() > 0) {
            workStopVO.setCopyPersons(copyPersonVOS);
        }

        //根据项目Id获取项目名以及项目编号
        String pkProject = workStopVO.getPkProject();
        ProjectVO projectVO = projectSimpleQuery.queryProject(pkProject);
        workStopVO.setProjectName(projectVO.getSname());
        workStopVO.setProjectCode(projectVO.getScode());

        //可能存在没有项目组织的项目档案，所以后面不再对其组织进行翻译。
        if(projectVO.getPkOrg() ==null){
            return workStopVO;
        }
        OrganizationVO organizationVO = organizationQuery.queryByPkSrc(RuntimeEnvironment.getTenantId(), projectVO.getPkOrg());
        if(organizationVO != null){
            workStopVO.setOrgName(organizationVO.getSname());
            workStopVO.setPkOrganization(organizationVO.getPkOrganization());
            workStopVO.setPkOrgSrc(organizationVO.getPkSrc());
        }

        //判断当前登录用户是否具有审批权限，用于前端控制按钮的显示
        workStopVO.setCanApprove(false);  //  默认不具备审批权限。
        boolean canApprove = iworkFlowService.checkApprovePerm(workStopVO.getPkWorkstopreport(), RuntimeEnvironment.getLoginUserId());
        if(canApprove){
            workStopVO.setCanApprove(true);
        }

        return workStopVO;
    }

    private void fillPics(WorkStopVO[] vos) throws BusinessException {
        List<String> entityies = new ArrayList<>();
        for (WorkStopVO workStopVO : vos) {
            entityies.add(workStopVO.getPkWorkstopreport());
        }
        Map<String, List<String>> entitiesForPic = picService.queryPicsByPkEntitys(entityies.toArray(new String[0]));
        for (WorkStopVO workStopVO : vos) {
            List<String> pics = entitiesForPic.get(workStopVO.getPkWorkstopreport());
            if (null == pics || pics.size() == 0) {
                continue;
            }
            workStopVO.setPictures(pics.toArray(new String[0]));
            workStopVO.setPicNum(pics.size());
        }
    }

    private void fillProjectNameAndCode(WorkStopVO[] workStopVOS) throws BusinessException {
        List<String> ids = new ArrayList<>();
        for (WorkStopVO workStopVO : workStopVOS) {
            ids.add(workStopVO.getPkProject());
        }
        if (null == ids && ids.size() == 0) {
            //do nothing
        } else {
            Map<String, ProjectVO> projectMap = projectSimpleQuery.queryProjects(ids.toArray(new String[0]));
            for (WorkStopVO workStopVO : workStopVOS) {
                ProjectVO projectVO = projectMap.get(workStopVO.getPkProject());
                if (null != projectVO) {
                    //赋值项目名
                    workStopVO.setProjectName(projectVO.getSname());
                    workStopVO.setProjectCode(projectVO.getScode());
                } else {
                    throw new BusinessException("项目没有查询到");
                }
            }
        }
    }

    private void wrapStatus(WorkStopVO workStopVO) {
        if (workStopVO.getBillstatus() != null) {
            switch (workStopVO.getBillstatus()) {
                case BillStatusConst.COMMON_APPROVING_STATUS:
                    workStopVO.setStatus("审批中");
                    workStopVO.setStrBillstatus("审批中");
                    break;
                case BillStatusConst.COMMON_REJECT_STATUS:
                    workStopVO.setStatus("驳回");
                    workStopVO.setStrBillstatus("驳回");
                    break;
                case BillStatusConst.COMMON_APPROVED_STATUS:
                    workStopVO.setStatus("审批通过");
                    workStopVO.setStrBillstatus("审批通过");
                    break;
                case BillStatusConst.COMMON_COMMIT_STATUS:
                    workStopVO.setStatus("驳回后再提交");
                    workStopVO.setStrBillstatus("驳回后再提交");
                    break;
                case BillStatusConst.COMMON_FREE_STATUS:
                    workStopVO.setStatus("自由态");
                    workStopVO.setStrBillstatus("自由态");
            }
        }
    }


}
